<template>
    <div class="list-container">
        <div v-for="(item, index) in list" :key="index" class="list-item" :style="{ backgroundColor: item.background }">
            {{ index }}
        </div>
        <div v-if="loading" class="list-loading">Loading...</div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue"
const list = ref([{ background: "rgb(233, 32, 38)" }])
const loading = ref(false)
const num = ref(10)
const loadedCount = ref(2)
const maxCount = ref(50)

const getList = () => {
    if(list.value.length >= maxCount.value || list.value.length >= maxCount.value - num.value) return
    loading.value = true
    setTimeout(() => {
        const data = generateData(num.value)
        list.value.push(...data)
        loadedCount.value += num.value
        loading.value = false
    }, Math.floor(Math.random() * 6) * 1000);
};

const handleScroll = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  const windowHeight = window.innerHeight;
  const documentHeight = document.documentElement.scrollHeight;
  if (scrollTop + windowHeight >= documentHeight && list.value.length < maxCount.value) {
    getList();
  }
}

const generateData = (num) => {
    const data = []
    for(let i = 0;i < num; i ++) {
        if(loadedCount.value + i >= maxCount.value) break
        data.push({ background: randomColor() })
    }
    return data
}

const randomColor = () => {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    return `rgb(${r}, ${g}, ${b})`;
};

onMounted(() => {
    getList(num.value);
    window.addEventListener("scroll", handleScroll);
});

onUnmounted(() => {
    window.removeEventListener("scroll", handleScroll);
});
</script>

<style scoped>
.list-container {
    display: flex;
    flex-wrap: wrap;
}

.list-item {
    width: 100%;
    height: 500px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 48px;
    color: #fff;
}

.list-loading {
    width: 100%;
    height: 50px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 24px;
    color: #ccc;
}
</style>